import { defineStore } from 'pinia'
import request from '@/utils/request'
import { IApiRes, Profile } from '@/types/data'
import { getProfile, removeProfile, setProfile } from '@/utils/Profile'

export default defineStore('user',{
   state:()=>{
    return{
      Profile:getProfile()  as Profile
    }
   },
   actions:{
    // 绑定当前的QQ和账号
    async qqBindLogin(openId: string, mobile: string, code: string) {
      const res = await request.post<IApiRes<Profile>>('/login/social/bind', {
        mobile,
        code,
        unionId: openId
      })
      // 1. 保存用户信息到 state 中
      this.Profile = res.data.result
      // 2. 持久化
      setProfile(res.data.result)
    },
    // 绑定qq的短信验证码
    async sendQQBindMsg(mobile: string) {
      await request.get('/login/social/code', {
        params: {
          mobile
        }
      })
    },
    // QQ联合登录
    async loginQQ(openId:string){
      const res = await request.post('/login/social',{unionId: openId, source: 6})
      console.log(res.data.result);
      this.Profile=res.data.result
      setProfile(res.data.result)
    },
    //  退出登陆
    logout(){
      //1.  删除pinia
      this.Profile = {} as Profile
      //2. 清空本地
      removeProfile()

    },
    // 账号密码登陆
    async login(data:{account:string,password:string}){
      const res = await request.post<IApiRes<Profile>>('/login',data)
      console.log(res.data.result);
      this.Profile=res.data.result
      setProfile(res.data.result)
    },
    // 手机号验证吗登陆
    async  mobileLogin(mobile: string, code: string){
      const res = await request.post<IApiRes<Profile>>('/login/code',{mobile,code})
      console.log(res.data.result);
      this.Profile=res.data.result
    },
    // 验证码接口
    async sendMobileMsg(mobile:string){
      const res = await request.get('/login/code',{
        params:{
          mobile:mobile
        }
      })
      console.log(res.data.result);
    },
  
   }
})